import axios from "./axios/axios";
import { isJSON } from "./util";
import config from './config';
import { server_url } from './env';

const instance = axios.create({
  baseURL: server_url,
  timeout: 5000,
  data: {},
  headers: {
    "Content-type": "application/x-www-form-urlencoded"
  }
})

//请求拦截
instance.interceptors.request.use(
  config => {
    config.startTime = +new Date();
    return config
  },
  err => {
    console.error(err)
    return Promise.reject(err)
  }
)

//响应拦截
instance.interceptors.response.use(
  res => {
    if(res.statusCode === 200){
      let config = res.config;
      let server_data = res.data;
      console.log(`请求时间：${(+new Date() - config.startTime) / 1000}s`)
      console.log(`请求地址：${config.url}`)
      console.log(`请求参数：${JSON.stringify(config.data)}`)
      console.log(`******************************返回结果********************************`)
      if(config.requestType === 'download'){
        console.log(res)
        return res;
      }
      // 判断服务器返回数据是不是【json字符串】
      if(isJSON(server_data)){
        server_data = JSON.parse(server_data)
      }
      console.log(server_data)
      if(server_data.code === 200){
        return server_data.data
      }
    }
    return res
  },
  err => {
    console.warn(err)
    return Promise.reject(err)
  }
)
// 将config地址配置为axios对象的方法，方便直接访问
for(let key in config){
  instance[key.replace("Url", "")] = function(opts){
    return instance.post(config[key], opts);
  }
} 

module.exports = instance;